<?php

namespace app\admin\controller;

use address\Address;
use app\common\controller\Backend;
use fast\Random;
use think\addons\Service;
use think\Cache;
use think\Config;
use think\Db;
use think\Lang;

/**
 * Ajax异步请求接口
 * @internal
 */
class Ajax extends Backend {

    protected $noNeedLogin = ['lang', 'area', 'upload'];
    protected $noNeedRight = ['*'];
    protected $layout = '';

    public function _initialize() {
        parent::_initialize();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);
    }

    /**
     * 解析地址接口
     */
//    public function addressResolve()
//    {
//        $text = $_POST['text'];
//        $ret = Address::smart_parse($text);
//        if (!$ret) {
//            $this->error(Address::$error);
//        } else {
//            $result = [
//                'province' => $ret['detail'][1]['id'],
//                'city' => $ret['detail'][2]['id'],
//                'area' => $ret['detail'][3]['id'],
//                'name' => $ret['name'],
//                'tel' => $ret['mobile'],
//                'really' => isset($ret['really'])?$ret['really']:'',
//                'unreally' => isset($ret['unreally'])?$ret['unreally']:'',
//            ];
//            $this->success('', null, $result);
//        }
//
//    }

        public function addressResolve()
    {
        $host = "https://kop.kuaidihelp.com/api";
        $method = "POST";
        $headers = array();
//        dump($_POST['text']);

        if (isset($_POST['text'])) {
//            $text = preg_replace('# #', '', $_POST['text']);
            $text = str_replace("\n"," ",$_POST['text']);
        } else {
            exit;
        }
        if (isset($_POST['multimode']) && $_POST['multimode']) {
            $multimode = 'true';
        } else {
            $multimode = 'false';
        }
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $ts = time();
        $bodys = [
            "app_id" => '101680',
            "method" => 'cloud.address.resolve',
            "sign" => md5('101680' . 'cloud.address.resolve' . $ts . 'c92a62f09fcebf5416a75019041a76e969c17eee'),
            "ts" => $ts,
            "data" => '{
                "text":"' . $text . '",
                "multimode":' . $multimode . '}'
        ];
        $bodys = http_build_query($bodys);
        $url = $host;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);

        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {
            $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $headerSize);
            $body = substr($result, $headerSize);
            $obj = json_decode($body);

            if ($obj->code == 0) {
                $obj = $obj->data[0];
                $ret = [
                    'province' => getArea($obj->province_shortname, 1),
                    'city' => getArea($obj->city_shortname, 2),
                    'area' => getArea($obj->county_shortname, 3),
                    'name' => $obj->name,
                    'tel' => $obj->mobile == '' ? $obj->phone : $obj->mobile,
                    'address' => $obj->detail,
                    'remark' => $obj->note
                ];
                $this->success('', null, $ret);
            } else {
                $this->error();
            }
        } else {
            $this->error();
        }
        exit;
    }


    /**
     * 加载语言包
     */
    public function lang() {
        header('Content-Type: application/javascript');
        $controllername = input("controllername");
        //默认只加载了控制器对应的语言名，你还根据控制器名来加载额外的语言包
        $this->loadlang($controllername);
        return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
    }

    /**
     * 上传文件
     */
    public function upload() {
        Config::set('default_return_type', 'json');
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
                (
                !in_array($suffix, $mimetypeArr) || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        $replaceArr = [
            '{year}' => date("Y"),
            '{mon}' => date("m"),
            '{day}' => date("d"),
            '{hour}' => date("H"),
            '{min}' => date("i"),
            '{sec}' => date("s"),
            '{random}' => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}' => $suffix,
            '{.suffix}' => $suffix ? '.' . $suffix : '',
            '{filemd5}' => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id' => (int) $this->auth->id,
                'user_id' => 0,
                'filesize' => $fileInfo['size'],
                'imagewidth' => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype' => $suffix,
                'imageframes' => 0,
                'mimetype' => $fileInfo['type'],
                'url' => $uploadDir . $splInfo->getSaveName(),
                'uploadtime' => time(),
                'storage' => 'local',
                'sha1' => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            $this->success(__('Upload successful'), null, [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 通用排序
     */
    public function weigh() {
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        //排序的方式
        $orderway = $this->request->post("orderway", 'strtolower');
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = 'id';
        $pid = $this->request->post("pid");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v['id'];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = $sour[$position];    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            $weighids[$n] = $weighdata[$offset];
            Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }
        $this->success();
    }

    /**
     * 清空系统缓存
     */
    public function wipecache() {
        $type = $this->request->request("type");
        switch ($type) {
            case 'content' || 'all':
                rmdirs(CACHE_PATH, false);
                Cache::clear();
                if ($type == 'content')
                    break;
            case 'template' || 'all':
                rmdirs(TEMP_PATH, false);
                if ($type == 'template')
                    break;
            case 'addons' || 'all':
                Service::refresh();
                if ($type == 'addons')
                    break;
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }

    /**
     * 读取品类数据,联动列表
     */
    public function orderCategory() {
        $level = $this->request->get('level');
        $categorylist = null;
        $where = [];
        switch ($level) {
            case '1': {
                    $where['pid'] = 0;
                };
                break;
            case '2': {
                    $where['pid'] = $this->request->get('first');
                };
                break;
            case '3': {
                    $where['pid'] = $this->request->get('second');
                };
                break;
        }
        $categorylist = Db::name('order_category')->where($where)->field('id as value,title as name')->order('weigh desc,id desc')->select();
        $this->success('', null, $categorylist);
    }

    /**
     * 读取分类数据,联动列表
     */
    public function category() {
        $type = $this->request->get('type');
        $pid = $this->request->get('pid');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid !== '') {
            if ($type) {
                $where['type'] = $type;
            }
            if ($pid) {
                $where['pid'] = $pid;
            }

            $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
        }
        $this->success('', null, $categorylist);
    }

    /**
     * 读取分类数据,联动列表
     */
    public function attribute() {
        $dataList = null;
        $where = [];
        $level = $this->request->get('level');
        switch ($level) {
            case '1': {
                    $where = ['pid' => 0];
                    $dataList = Db::name('order_category')->where($where)->field('id as value,title as name')->order('weigh desc,id desc')->select();
                }break;
            case '2': {
                    $where = ['pid' => $this->request->get('first')];
                    $dataList = Db::name('order_category')->where($where)->field('id as value,title as name')->order('weigh desc,id desc')->select();
                }break;
            case '3': {
                    $where = ['pid' => $this->request->get('second')];
                    $dataList = Db::name('order_category')->where($where)->field('id as value,title as name')->order('weigh desc,id desc')->select();
                }break;
            case '4': {
                    if (!$this->request->get('category_id')) {
                        break;
                    }
                    $where['category_id'] = $this->request->get('category_id');
                    $dataList = Db::name('order_attribute')->where($where)->field('id as value,title as name')->order('weigh desc,id desc')->select();
                }break;
        }


        $this->success('', null, $dataList);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area() {
        $province = $this->request->get('province');
        $city = $this->request->get('city');
        $where = ['pid' => 0, 'level' => 1];
        $provincelist = null;
        if ($province !== '') {
            if ($province) {
                $where['pid'] = $province;
                $where['level'] = 2;
            }
            if ($city !== '') {
                if ($city) {
                    $where['pid'] = $city;
                    $where['level'] = 3;
                }
                $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
            }
        }
        $this->success('', null, $provincelist);
    }

}
